package com.chat.interceptor;

import com.chat.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final UserDao userDao;

    @Autowired
    public LoginInterceptor(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Cookie[] cookies=request.getCookies();
        Cookie sid=null;
        Cookie user=null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("SID")) {
                sid = cookie;
            } else if (cookie.getName().equals("USER")) {
                user = cookie;
            }
        }

        if(sid==null||user==null) return false;

        //如果通过验证则返回true
        return sid.getValue().equals(userDao.getCertificate(user.getValue()));
    }
}
